<template>
  <el-dialog v-model="showCapDialog" title="人机验证" width="350px" @open="handleOpen">
    <drag-verify-img-chip ref="dragVerifyImgChipRef" @getImg="getImg" @validImg="validImg" />
  </el-dialog>
</template>

<script setup>
import { reactive, computed, ref } from 'vue'
import { getVerificationImage, humanVerify } from '@/api/verify'
import { ElMessage } from 'element-plus'

const props = defineProps({
  show: {
    type: Boolean,
    default: false
  }
})
const emits = defineEmits(['onSuccess', 'update:show'])

const dragVerifyImgChipRef = ref(null)
const showCapDialog = computed({
  get() {
    return props.show
  },
  set(val){
    console.log('set', val)
    emits('update:show', val)
  }
})
const captchaInfo = reactive({
  type: 2,
  x: 0,
  y: 0
})
// 获取滑动验证码图片
const getImg = (callback) => {
  getVerificationImage({ type: 2 }).then((res) => {
    captchaInfo.y = res.data.y
    let obj = {
      captcha: {
        backgroundImage: `data:image/png;base64, ${res.data.shadeImage}`,
        sliderImage: `data:image/png;base64, ${res.data.cutoutImage}`,
      },
      id: new Date().getTime()
    }
    callback(obj)
  }, error => {
    callback(error)
  })
}
// 操作滑动后返回值，并传去后端验证
const validImg = async (movePercent, id, callback) => {
  captchaInfo.x = movePercent * 280
  await humanVerify(captchaInfo).then(res => {
    if(res.data){
      callback(true)
      emits('onSuccess')
      emits('update:show', false)
    }else{
      ElMessage.error('验证失败')
      callback(false)
    }
  })
}

const handleOpen = () => {
  dragVerifyImgChipRef?.value.reset()
}
</script>

<style lang="scss">
.el-dialog__body{
  padding: 5px;
}
</style>